package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 用户服务层方法
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 新增或更新用户业务方法
     *
     * @param user 前端传递用户封装信息
     */
    @Override
    public void saveOrUpdate(User user) {
        if (user.getId() != null) {
            //编辑操作，mapper.xml中密码/邮箱（用户账号）更新单独处理
            userMapper.updateByPrimaryKey(user);
        } else {
            //1、判断邮箱是否被注册
            Map<String, Object> temp = userMapper.selectByEmailAndPassword(user.getEmail(), null);
            if (temp != null) {
                //2、被注册通过抛出异常传递结果信息
                throw new RuntimeException("亲，此邮箱已被注册，可以直接登录");
            } else {
                //3、未注册则保存用户信息（增加默认属性值）
                user.setGender(User.GENDER_SECRET);
                user.setHeadImgUrl("/img/user/head.jpg");
                user.setCoverImgUrl("/img/user/bg.jpeg");
                userMapper.insert(user);
            }

        }
    }

    @Override
    public Map<String, Object> login(User user) {

        if (StringUtils.hasLength(user.getEmail())&&StringUtils.hasLength(user.getPassword())) {
            Map<String, Object> map = userMapper.selectByEmailAndPassword(user.getEmail(), user.getPassword());
            if (map == null) {
                //无用户信息，抛出登录异常
                throw new RuntimeException("账号与密码不匹配，请重新输入");
            } else {
                //设置到session中
                UserContext.setCurrentUser(map);
            }
            return map;
        }
        throw new RuntimeException("账号或密码为空");
    }

    /**
     * 用户列表业务方法
     * @param queryObject 前端传入的参数封装对象
     * @return 分页查询数据封装对象
     */
    @Override
    public PageInfo<User> query(QueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(), queryObject.getPageSize());
        List<User>list=userMapper.selectForList(queryObject);
        return new PageInfo<>(list);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
